package com.ayf.payment.game.api.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.entity.Merchant;
import com.ayf.payment.game.api.entity.MerchantSign;
import com.ayf.payment.game.api.eqb.comm.SignDTO;
import com.ayf.payment.game.api.eqb.service.EQBService;
import com.ayf.payment.game.api.exception.LogicalException;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.service.MerchantSignService;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.QrCodeUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zh-liang
 * @Date : 2021-01-04 13:22
 */
@RestController
@RequestMapping("/v/merchant")
public class MerchantSignController {

    @Resource
    private EQBService eqbService;
    @Resource
    private MerchantSignService merchantSignService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private MerchantService merchantService;

    public static final String url = System.getenv("AYF_API_EQB_MERCHANT_HOST") + "/gameapip/v/merchant/getUrl?k=";

    /**
     * 查询签约状态
     */
    @GetMapping("/getSignStatus")
    public CommonResult<MerchantSign> getSignStatus(MerchantDTO merchantDTO) {
        MerchantSign sign = merchantSignService.getMerSignInfo(merchantDTO.getId());
        if (StrUtil.isEmpty(sign.getPhone())) {
            Merchant merchant = new Merchant();
            merchant.setId(merchantDTO.getId());
            MerchantDTO dto = merchantService.selectOne(merchant);
            sign.setPhone(dto.getPhone());
        }
        if (StrUtil.isEmpty(sign.getEmail())) {
            Merchant merchant = new Merchant();
            merchant.setId(merchantDTO.getId());
            MerchantDTO dto = merchantService.selectOne(merchant);
            sign.setEmail(dto.getEmail());
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询签约状态", sign);
    }

    /**
     * 获取签约二维码
     *
     * @return
     */
    @PostMapping("/getSignQrCode")
    public CommonResult<String> getSignQrCode(MerchantDTO merchantDTO, @RequestBody SignDTO signDTO, HttpServletResponse response) {
        try {
            signDTO.setMerchantId(merchantDTO.getId());
            if (StrUtil.isEmpty(signDTO.getName())) {
                throw new ParameterException("姓名不能为空");
            }
            if (StrUtil.isEmpty(signDTO.getIdCardNo())) {
                throw new ParameterException("身份证号不能为空");
            }
            if (!IdcardUtil.isValidCard(signDTO.getIdCardNo())) {
                throw new ParameterException("身份证号格式错误");
            }
            if (StrUtil.isEmpty(signDTO.getPhone())) {
                throw new ParameterException("手机号不能为空");
            }
            if (!Validator.isMobile(signDTO.getPhone())) {
                throw new ParameterException("手机号格式错误");
            }
            if (StrUtil.isEmpty(signDTO.getEmail())) {
                throw new ParameterException("邮箱不能为空");
            }
            if (!Validator.isEmail(signDTO.getEmail())) {
                throw new ParameterException("邮箱格式错误");
            }
//            merchantSignService.updateMerSign2(signDTO);
//            MerchantSign merSignInfo = merchantSignService.getMerSignInfo(merchantDTO.getId());
//            signDTO.setChannelAccountId(merSignInfo.getChannelAccountId());
            String signUrl = eqbService.getSignUrl(signDTO);
            if (StrUtil.isNotEmpty(signUrl)) {
                LogPortal.info("用户：{} {} {}获取签署协议URL成功，url:[{}]", merchantDTO.getId(), signDTO.getName(),
                        signDTO.getIdCardNo(), signUrl);
            } else {
                String traceId = SnowFlakeUtils.getTraceId();
                throw new ParameterException("错误码：" + traceId);
            }
            String key = "eqb_sign_url_" + merchantDTO.getId() + "_" + UUID.randomUUID().toString().replaceAll("_", "").substring(0, 6);
            redisCacheUtil.setObjectToCache(key, signUrl, 2L, TimeUnit.DAYS);
            String base64 = QrCodeUtils.encodeToBase64(url + key, false);
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取成功", base64);
        } catch (ParameterException e) {
            throw e;
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            throw new LogicalException("{} 商户：{}获取签约二维码失败,发生 {} 异常,异常信息为 {}", traceId, merchantDTO.getId(), e.getClass().getSimpleName(), e.getMessage());
        }
    }

    /**
     * 查询签约状态
     */
    @GetMapping("/getUrl")
    public String getUrl(@RequestParam("k") String k, HttpServletResponse response) {
        String url = redisCacheUtil.getObjectFromCache(k);
        if (StrUtil.isEmpty(url)) {
            return "二维码已过期，请重新获取";
        }
        try {
            response.sendRedirect(url);
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            LogPortal.error("{} k: {} url: {} 重定向到签署页面失败，发生 {} 异常，异常信息为 {}", e, traceId, k, url, e.getClass().getSimpleName(), e.getMessage());
            return "错误码：" + traceId;
        }
        return "ok";
    }
}
